package com.paishen.peiniwan.module.message;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;

import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.User;
import com.paishen.peiniwan.database.UserDao;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.HttpResp;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.DateInfo;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.peiniwan.module.date.DateInfoActivity;
import com.paishen.peiniwan.module.date.DateInfoSimpleActivity;
import com.paishen.peiniwan.module.date.DateStartActivity;
import com.paishen.peiniwan.module.profile.ProfileBalanceChargeActivity;
import com.paishen.peiniwan.module.profile.ProfileInfoActivity;
import com.squareup.okhttp.Request;

import java.io.ByteArrayInputStream;

import de.greenrobot.event.EventBus;

public class EaseChatActivity extends BaseActivity {

    public static final int REQUEST_CODE_SIMPLE_DATE = 11301;

    private EaseChatFragment chatFragment;
    private String toChatUsername;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        //聊天人或群id
        toChatUsername = getIntent().getExtras().getString(EaseConstant.EXTRA_USER_ID);
        if (TextUtils.isEmpty(toChatUsername)) {
            BaseUtil.showToast(R.string.error_data);
            finish();
            return;
        }
        isSupportTouchBack = false;

        FrameLayout container = new FrameLayout(this);
        container.setId(R.id.lay_container);
        setContentView(container);

        //可以直接new EaseChatFratFragment使用
        chatFragment = new EaseChatFragment();
        //传入参数
        chatFragment.setArguments(getIntent().getExtras());
        chatFragment.setChatFragmentListener(new EaseChatFragment.EaseChatFragmentListener() {
            @Override
            public void onSetMessageAttributes(EMMessage message) {
            }

            @Override
            public void onEnterToChatDetails() {
            }

            @Override
            public void onAvatarClick(String username) {
                UserDao userDao = App.i().getCurrDaoSession().getUserDao();
                com.paishen.peiniwan.database.User dbUser = userDao.queryBuilder().where(UserDao.Properties.Easemob_username.eq(username)).unique();
                if (dbUser != null) {
                    Intent intent = new Intent(EaseChatActivity.this, ProfileInfoActivity.class);
                    intent.putExtra(ProfileInfoActivity.EXTRA_SHOWN_USER_ID, dbUser.getId());
                    intent.putExtra(ProfileInfoActivity.EXTRA_MODE_CHAT, true);

                    startActivity(intent);
                }
            }

            @Override
            public boolean onMessageBubbleClick(EMMessage message) {
                switch (message.getType()) {
                    case TXT:
                        try {
                            String mType = message.getStringAttribute(EaseConstant.TYPE);
                            if (TextUtils.equals(mType, EaseConstant.TYPE_DATE)) {
                                requestOrderInfo(Long.parseLong(message.getStringAttribute(EaseConstant.PARAMS_ORDER_ID)));
                            }
                        } catch (Exception e) {
                        }
                        break;
                }
                return false;
            }

            @Override
            public void onMessageBubbleLongClick(EMMessage message) {
            }

            @Override
            public boolean onExtendMenuItemClick(int itemId, View view) {
                return false;
            }

            @Override
            public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
                return null;
            }

            @Override
            public void onDateClick() {
                Intent intent = new Intent(EaseChatActivity.this, DateStartActivity.class);
                intent.putExtra(DateStartActivity.EXTRA_MODE_SIMPLE, true);
                intent.putExtra(DateStartActivity.EXTRA_SIMPLE_OTHER_EASE_ID, toChatUsername);
                startActivityForResult(intent, REQUEST_CODE_SIMPLE_DATE);
            }

            @Override
            public void onGiftClick(long giftId, String name, int value, View v) {
                requestOrderSendGift(toChatUsername, giftId, name, value);
            }

            @Override
            public void onChargeClick() {
                Intent intent = new Intent(EaseChatActivity.this, ProfileBalanceChargeActivity.class);
                startActivity(intent);
            }

            @Override
            public float onBalanceInit() {
                Float mAmount = App.i().getUser().getAmount();
                return mAmount != null ? mAmount.floatValue() : 0;
            }
        });
        getSupportFragmentManager().beginTransaction().add(R.id.lay_container, chatFragment).commit();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_MAIN_MESSAGE_CLEAR_READ));
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // 点击notification bar进入聊天页面，保证只有一个聊天页面
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CODE_FOR_CAMERA_PERMISSION) {
            if (permissions[0].equals(Manifest.permission.CAMERA)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                chatFragment.selectPicFromCamera();
            } else {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                    AlertDialog dialog = new AlertDialog.Builder(this)
                            .setMessage(com.paishen.common.R.string.request_permission_camera)
                            .setPositiveButton(com.paishen.common.R.string.go_1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                    startActivity(intent);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton(com.paishen.common.R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    dialog.show();
                }
            }
        } else if (requestCode == CODE_FOR_PHOTO_PERMISSION) {
            if (permissions[0].equals(Manifest.permission.CAMERA)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                chatFragment.selectPicFromLocal();
            } else {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                    AlertDialog dialog = new AlertDialog.Builder(this)
                            .setMessage(com.paishen.common.R.string.request_permission_photo)
                            .setPositiveButton(com.paishen.common.R.string.go_1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                    startActivity(intent);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton(com.paishen.common.R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    dialog.show();
                }
            }
        } else if (requestCode == CODE_FOR_LOCATION_PERMISSION) {
            if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // onLocationGranted
            } else {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                    AlertDialog dialog = new AlertDialog.Builder(this)
                            .setMessage(com.paishen.common.R.string.request_permission_location)
                            .setPositiveButton(com.paishen.common.R.string.go_1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                    startActivity(intent);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton(com.paishen.common.R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    dialog.show();
                    return;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SIMPLE_DATE) {
            if (resultCode == RESULT_OK) {
                long mOrderId = data.getLongExtra(DateStartActivity.EXTRA_SIMPLE_ORDER_ID, 0);
                String mSubject = data.getStringExtra(DateStartActivity.EXTRA_SIMPLE_ORDER_SUBJECT);
                String mTime = data.getStringExtra(DateStartActivity.EXTRA_SIMPLE_ORDER_TIME);
                String mAddress = data.getStringExtra(DateStartActivity.EXTRA_SIMPLE_ORDER_ADDRESS);
                chatFragment.sendDateMessage(mOrderId, mSubject, mTime, mAddress);
            }
        } else {
            chatFragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void requestOrderSendGift(String sendToEaseUserName,final long giftId, final String name, final int price) {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();
        PnwHttpManager.Order.sendGift(TAG, sendToEaseUserName, giftId, new PnwOkCallbackAdapter<HttpResp>() {
            @Override
            public void onResponse(HttpResp response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    chatFragment.sendGiftMessage(giftId, name, price);
                    User login = App.i().getUser();
                    login.setAmount(login.getAmount() - price);
                    chatFragment.setBalanceForGift(login.getAmount());
                    EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, login));
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    private void requestOrderInfo(long orderId) {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();
        PnwHttpManager.Order.info(TAG, orderId, new PnwOkCallbackAdapter<HttpRespData<DateInfo>>() {
            @Override
            public void onResponse(HttpRespData<DateInfo> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    if (response.data.book == null || response.data.book.size() < 1) {
                        BaseUtil.showToast(R.string.error_data);
                    } else {
                        Intent intent = new Intent(EaseChatActivity.this, response.data.status == C.date.WAIT_RESPONSE_1 ? DateInfoSimpleActivity.class : DateInfoActivity.class);
                        // fixed price
                        response.data.book.get(0).unit_price = response.data.price;
                        intent.putExtra(DateInfoActivity.EXTRA_DATE_INFO, response.data);
                        startActivity(intent);
                    }
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    public void onEventMainThread(com.paishen.peiniwan.BusEvent event) {
        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                case BusEvent.ACTION_REFRESH_EASE_NEW_GIFT:
                    User login = App.i().getUser();
                    chatFragment.setBalanceForGift(login.getAmount());
                    break;
            }
        }
    }

}
